<?php

namespace App\Http\Controllers\Api;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    //

    /**
     * 登录，新增或修改用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addOrUpdate(Request $request) {

        $wechat = app('wechat.mini_program');
        $res = $wechat->auth->session($request->code?:'');
        $input = $request->all();
        if(isset($res['errcode']) && $res['errcode'] > 0) return $this->apiError($res['errmsg']);
        $open_id = $res['openid'];
        $validateResult = $this->validateCreateUser($input);
        if ($validateResult["errorCode"] > 0) {
            return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        }

        $user = User::where('open_id', $open_id)->first();
        if(empty($user)){
            $user = new User();
            $user->open_id = $open_id;
        }
        if(!empty($input['profile'])) $user->profile = $input['profile'];
        if(!empty($input['nick_name'])) $user->nick_name = $input['nick_name'];

        $user->save();

        $data = [
            'user' => $user
        ];
        return $this->apiSuccess($data);
    }

    private function validateCreateUser($input) {
        $name = isset($input['name']) ? $input['name']: '';
        $mobile = isset($input['mobile']) ? $input['mobile']: '';
        if(!empty($mobile)){
            return [
                "message" => "手机格式有误",
                "errorCode" => 5000
            ];
        }
        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }
}
